'''Simple data loader module.

Loads data files from the "data" directory shipped with a game.

Enhancing this to handle caching etc. is left as an exercise for the reader.
'''

import os
import pyglet

data_py 	= os.path.abspath(os.path.dirname(__file__))
sound_dir 	= os.path.normpath(os.path.join(data_py,  'sounds'))
image_dir	= os.path.normpath(os.path.join(data_py,  'images'))

_images = {}
_sounds = {}

def imagepath(filename):
	'''Determine the path to a file in the data directory.
	'''
	return os.path.join(image_dir, filename)

def soundpath(filename):
	'''Determine the path to a file in the data directory.
	'''
	return os.path.join(sound_dir, filename)


'''	image_path = os.path.join('images')
	images = [os.path.join(image_path, f) for f in os.listdir(image_path) if f.endswith('.png')]
	images = [pyglet.image.load(path) for path in images]
'''
def loadimages():
	'''Load all of the images in the image dir'''
	for f in os.listdir(image_dir):
		if f.endswith('.png'):
			image(f)

def image(filename):
	"""Return an image loaded from the data directory"""
	global _images
	if filename not in _images:
		_images[filename] = pyglet.image.load(imagepath(filename))
	return _images[filename]

def return_list_images():
	'''Hack to turn dict into list, this code needs to be refactored for animation
	or perhaps code should be factored to take a list of images file names and return
	corresponding list of images'''
	images = []

	for i in _images:
		images.append(_images[i])
	return images

def sound(filename):
	"""Return a sound loaded from the data directory"""
	global _sounds
	if filename not in _sounds:
		_sounds[filename] = pyglet.media.load(soundpath(filename), streaming=False)
	return _sounds[filename]

def texture(filename):
	"""Return a texture loaded from the data directory"""
	return image(filename).get_texture()
